package com.onurokan.someone4me.user.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.onurokan.someone4me.user.dao.UserDao;
import com.onurokan.someone4me.user.domain.User;

@Service("hibernateUserDetailsService")
public class HibernateUserDetailsServiceImpl implements UserDetailsService {

	@Autowired
	private UserDao userDao;

	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {

		if (username == null || username.isEmpty()) {
			throw new UsernameNotFoundException("Username can not be empty!");
		}

		User user = userDao.loadUserByUsername(username);

		if (user == null) {
			throw new UsernameNotFoundException("User is not found: "
					+ username);
		} else {
			if (user.getPassword() == null || user.getPassword().isEmpty()) {
				throw new UsernameNotFoundException("Password is not found");
			}
		}

		return user;
	}
}
